package com.sea.onlinejudge.common.exception;


import com.sea.onlinejudge.common.BaseData;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.MalformedJwtException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


@RestControllerAdvice
public class MyExceptionHandler {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @ExceptionHandler(Exception.class)
    public BaseData handlerException(Exception e) {
        logger.error(e.getMessage(), e);
        return BaseData.error();
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public BaseData handleDuplicateKeyException(DuplicateKeyException e){
        logger.error(e.getMessage(), e);
        return BaseData.error("数据库中已存在该记录");
    }

    @ExceptionHandler(JwtException.class)
    public BaseData handlerJwtException(JwtException e) {
        logger.error(e.getMessage(), e);
        return BaseData.error(HttpStatus.UNAUTHORIZED.value(), "Token出错");
    }

    @ExceptionHandler(MalformedJwtException.class)
    public BaseData handlerMalformedJwtException(MalformedJwtException e) {
        logger.error(e.getMessage(), e);
        return BaseData.error(HttpStatus.UNAUTHORIZED.value(), "Token解析错误");
    }

    @ExceptionHandler(MException.class)
    public BaseData handlerMException(MException e) {
        logger.error(e.getMsg(), e);
        return BaseData.error(e.getCode(), e.getMsg());
    }

    @ExceptionHandler(ExpiredJwtException.class)
    public BaseData handlerExpiredJwtException(ExpiredJwtException e) {
        logger.error(e.getMessage(), e);
        return BaseData.error(HttpStatus.UNAUTHORIZED.value(), "Token过期");
    }
}
